package com.ac.conf;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.annotation.PostConstruct;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.ac.model.FileLog;
import com.ac.service.AuthTokenService;
import com.ac.service.FileLogService;

@Component
class FileFilter implements Filter {

	@Autowired
	AuthTokenService ts;

	@Autowired
	FileLogService FileLogService;

	private static FileFilter fileFilter;

	@PostConstruct
	public void init() {
		fileFilter = this;
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		try {
			ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
					.getRequestAttributes();
			HttpServletRequest request = attributes.getRequest();
//			String Host = request.getHeader("Host");
//			String Referer = request.getHeader("Referer");
			String url = request.getRequestURL().toString();// 获取访问全地址
			url = url.split("static_file/upload/")[1];// 截取文件地址
			String userIdReq = url.split("/")[0];// 获取用户id
			String[] sp1 = url.split("/")[1].split("\\.");// 获取文件全称
			String fileName = sp1[0];// 文件名
			String type = sp1[1];// 文件后缀
			FileLog fileLog = new FileLog();// 文件日志对象
			fileLog.setName(fileName);
			fileLog.setType(type);
			fileLog.setUserId(userIdReq);
			FileLog fileLogInfo = fileFilter.FileLogService.info(fileLog);// 查询文件存储权限
			if (fileLogInfo.isOpen())// 权限为开放
				filterChain.doFilter(servletRequest, servletResponse);// 对文件流放行
			else {// 不开放需要验证访问用户是否一致
				String token = request.getHeader("token");
				String userId = fileFilter.ts.getUserId(token);// 通过token获取用户id
				if (userId.equals(userIdReq))// 一致时放行
					filterChain.doFilter(servletRequest, servletResponse);
			}
		} catch (Exception e) {
		}
		String str = "<h1 style=\"color:red\">File not found or not authorized...<a href=\"http://www.346e.com\">To Home</a></h1>";
		InputStream input = new ByteArrayInputStream(str.getBytes());
		IOUtils.copy(input, servletResponse.getOutputStream());
	}
}